package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper mapper;


    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public List<?> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Permission> list = mapper.queryForList(qo);
        return new PageResult(total, list);
    }

    @Override
    public List<Permission> getPermissionByRoleId(Long id) {
        return mapper.getPermissionByRoleId(id);
    }

    @Override
    public List<String> getPermissionsByEmployeeId(Long id) {
        return mapper.getPermissionsByEmployeeId(id);
    }

    @Autowired(required = false)//如果为true则表示,规定必须有方法是要贴权限注解
    private RequestMappingHandlerMapping mapping;

    public void reload() {
        //获取全部注解用于排重
        List<Permission> permissions = mapper.selectAll();
        //使用set集合将权限中所有的resource封装进去
        Set<String> resources = new HashSet<>();
        for (Permission permission : permissions) {
            resources.add(permission.getResource());
        }

        //获取所有贴有RequestMapping的注解
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        for (HandlerMethod value : values) {
            RequiresPermissions annotation = value.getMethodAnnotation(RequiresPermissions.class);
            if (annotation != null) {
                if (!resources.contains(annotation.value()[1])) {
                    Permission permission = new Permission();
                    //0索引是权限的名称
                    permission.setName(annotation.value()[0]);
                    // 1索引权限的表达式
                    permission.setResource(annotation.value()[1]);

                    mapper.insert(permission);
                }
            }
        }
    }
}